var parkOrgparkJs = function(targetObj){
    this.sysUtils = new kendoUtils();
    this.targetObj = targetObj;
    this.targetObj['special']=true;
    this.init();
    return this;
};


var chargeBinfo = function(id, $list) {
    if (id == undefined || !id) {
        this.id = "d-" + new Date().getTime();
    } else {
        this.id = id;
    }
    this.$list = $list;
    return this;
}
chargeBinfo.prototype = {
    addToList : function($p) {
        $p.createTr(this.$list.find("tbody"));
    }
}
parkOrgparkJs.prototype={
    init:function(){
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [
            {fName:"saveparkOrg",fs:this.saveparkOrg},
            {fName:"createRow",fs:this.createRow},
            {fName:"cancel",fs:parkTree.resetTree},
            {fName:"deleteRow",fs:this.deleteRow}];
        this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
        this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
        //this.loadTab();
		//	this.showOff();
        //通行模式
        var trafficOpions = Utils.getModelValueByModelKey(BASIS.TRAFFIC_PATTERNS.TRAFFIC_PATTERNS_IC);
        Utils.createDataDictDropDownList([{div:this.targetObj.find("#trafficPatterns"),parentModelKey:BASIS.TRAFFIC_PATTERNS.ROOT,select:trafficOpions}],this);
        this.loadParkinfo();
    },
    loadParkinfo:function (e) {
        var that = this;
        that.editResult = null;
        that.isEdit = null;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
        var selectNode = zTree.getSelectedNodes()[0];
        var id = selectNode.id;
        JsonpAjax(baseApiPath+"facilities/parkInfo?organizationCode="+id,null,"json",function(result){
            that.editResult = result;
            that.sysUtils.setVariantBindFieldValue(result);
            that.setswitchCss();
            /*车位分布html生成*/
            var titleHtml = '',tbodyHtml='',endHtml='';
            titleHtml +='<tr><th style="text-align:center;">分区信息</th>';
            for(var o=0,l=result.cartypes.length;o<l;o++){
                titleHtml += '<th style="text-align:center;">'+result.cartypes[o].modelName+'</th>';
            }
            titleHtml+='<th style="text-align:center;">合计</th></tr>';
            that.targetObj.find("#titleList").append(titleHtml);


            for(var o=0,l=result.statistics.length;o<l;o++){
                var midHtml = '';

                for(var p=0,s=result.cartypes.length;p<s;p++){
                    jQuery.each(result.statistics[o], function(i, val) {
                        if(i == result.cartypes[p].modelKey.replaceAll('_','')){
                            midHtml +='<td style="width:16%">'+val+'</td>';
                        }
                    });
                }
                var trHtml = '<tr class="bgBlue"><td style="width:20%">'+result.statistics[o].name+'</td>'+midHtml+
                    '<td style="width:16%">'+result.statistics[o].count+'</td></tr>';

                tbodyHtml+=trHtml;
            }
            that.targetObj.find("#listView").append(tbodyHtml);
            endHtml +='<tr class="bgBlue"><td style="width:20%">车位分类统计</td>';

            for(var i =0;i<result.cartypes.length+1;i++){
                var totalRow = 0;
                that.targetObj.find('#listView tr').each(function() {
                    $(this).find('td:eq('+(parseFloat(i)+1)+')').each(function(){
                        totalRow += parseFloat($(this).text());
                    });
                });
                endHtml+='<td style="width:16%">'+totalRow+'</td>';
            }
            endHtml+='</tr>';
            that.targetObj.find("#listView").append(endHtml);
        },false);
        JsonpAjax(baseApiPath+"chargeStandard/chargeOptions?chargeType=1",null,"json",function(result){
            that.chargeList = result;
//				Utils.createAjaxDropDownList({div:that.targetObj.find("#workingDaysStandard"),select:result,unshift:false},that);
//				Utils.createAjaxDropDownList({div:that.targetObj.find("#holidaySeasonStandard"),select:result,unshift:false},that);
        },false);
        if(null == that.editResult){
            var charge_list = that.targetObj.find("#charge_list > tbody");
            $(Utils.getModelArrayByParentModelKey(BASIS.VEHICLE_TYPE.ROOT)).each(function(index){
                that.createTr(charge_list,index,null,this.modelKey);
            });
            that.sysUtils.mvvmModel.set("equipmentManagements_params_tipsMonth",3);
            that.sysUtils.mvvmModel.set("equipmentManagements_params_tipsDay",15);
            return; //新增啥都不需要做
        }
        var arrayinfo = null;
        if(undefined != that.editResult && undefined != that.editResult.equipmentManagements && undefined != that.editResult.equipmentManagements.charge){
        	arrayinfo = that.editResult.equipmentManagements.charge.chargelist
        }
//			if (arrayinfo == undefined || Object.getOwnPropertyNames(arrayinfo).length < 1) {
//			parkTree.hideMask();
//			return;
//			}
        var map = new Map();
        if(isNotEmpt(arrayinfo)){
            for (var i = 0,l=Object.getOwnPropertyNames(arrayinfo).length; i < l; i++) {
                var key = "charge"+i;
                if(arrayinfo.hasOwnProperty(key)){
                    var item = eval('(' + arrayinfo[key] + ')');
                    map.put(item["carType"], item);
                }
            }
        }
        var charge_list = that.targetObj.find("#charge_list > tbody");
        $(Utils.getModelArrayByParentModelKey(BASIS.VEHICLE_TYPE.ROOT)).each(function(index){
            that.createTr(charge_list,index,map.get(this.modelValue),this.modelKey);
        });
//			for (var i = 0,l=Object.getOwnPropertyNames(arrayinfo).length; i < l; i++) {
//			var key = "charge"+i;
//			if(arrayinfo.hasOwnProperty(key)){
//			var item = eval('(' + arrayinfo[key] + ')');
//			that.createTr(that.targetObj.find("#charge_list > tbody"),i,item);
//			}

//			}
        parkTree.hideMask();
        var setting = Utils.getModelValueByModelKey(BASIS.TRAFFIC_PATTERNS.TRAFFIC_PATTERNS_IC);
    },
    setswitchCss:function () {
        var that = this;
        that.targetObj.find(".checkbox input[type='checkbox']").each(function () {
            $(this).click(function(){
                this.value= this.value !=1 ? 1 : 0;
                if(this.id == 'calflag'){
					//parkOrg.showOff();
                var calcheck = that.targetObj.find('#calflag').val() == 'on' ? false : that.targetObj.find('#calflag').val() == 0 ? false : true;
                that.selectDisable(calcheck);
                }else if(this.id == 'startWxPay'){
                    var startWxPay = that.targetObj.find('#startWxPay').val() == 'on' ? false : that.targetObj.find('#startWxPay').val() == 0 ? false : true;
                    if(startWxPay){
                        that.targetObj.find('#showWx').show();
                    }else{
                        that.targetObj.find('#showWx').hide();
                    }
                }
            });
            if(this.id == 'startWxPay'){
                var startWxPay = that.targetObj.find('#startWxPay').val() == 'on' ? false : that.targetObj.find('#startWxPay').val() == 0 ? false : true;
                if(startWxPay){
                    that.targetObj.find('#showWx').show();
                }else{
                    that.targetObj.find('#showWx').hide();
                }
            }
            if(this.value == 1){
                this.checked=true;
            }else{
                this.value=0;
                this.checked=false;
            }
            var bindS = $(this).attr('data-bind');
            that.sysUtils.mvvmModel.set(bindS.substr(bindS.indexOf(':')+1,bindS.length),this.value);
        });
    },
    showOff:function () {
        layer.closeAll();
        var that = this;
        var calcheck = that.targetObj.find('#calflag').val() == 'on' ? false : that.targetObj.find('#calflag').val() == 0 ? false : true;
//			var difcheck = that.targetObj.find('#difflag').val() == 'on' ? false : that.targetObj.find('#difflag').val() == 0 ? false : true;
        if(calcheck){//
            that.targetObj.find('#one').hide();
            that.targetObj.find('#two').hide();
            that.targetObj.find('#workingDaysStandard').prop('required',false);
            that.targetObj.find('#holidaySeasonStandard').prop('required',false);
            that.targetObj.find('#three').show();
        }else if(!calcheck){//
            that.targetObj.find('#workingDaysStandard').prop('required',false);
            that.targetObj.find('#holidaySeasonStandard').prop('required',false);
            that.targetObj.find('#one').hide();
            that.targetObj.find('#two').hide();
            that.targetObj.find('#three').show();
        }
//			else if(calcheck && !difcheck){
//			that.targetObj.find('#workingDaysStandard').prop('required',true);
//			that.targetObj.find('#holidaySeasonStandard').prop('required',true);
//			that.targetObj.find('#one').show();
//			that.targetObj.find('#two').show();
//			that.targetObj.find('#three').hide();
//			}else{
//			that.targetObj.find('#workingDaysStandard').prop('required',true);
//			that.targetObj.find('#holidaySeasonStandard').prop('required',false);
//			that.targetObj.find('#one').show();
//			that.targetObj.find('#two').hide();
//			that.targetObj.find('#three').hide();
//			}
        that.selectDisable(calcheck);
    },
    selectDisable:function (calcheck) {
        var $this = this;
        this.targetObj.find("#charge_list tbody tr").each(function(){
            if(calcheck){
                $(this).find('td').eq(1).hide();
                $(this).find('td').eq(2).show();
                $(this).find('td').eq(3).show();
                $(this).find('td').eq(1)[0].children[0].required =false;
                $(this).find('td').eq(2)[0].children[0].required =true;
                $(this).find('td').eq(3)[0].children[0].required =true;
            }else if(!calcheck) {
                $(this).find('td').eq(1).show();
                $(this).find('td').eq(2).hide();
                $(this).find('td').eq(3).hide();
                $(this).find('td').eq(1)[0].children[0].required =true;
                $(this).find('td').eq(2)[0].children[0].required =false;
                $(this).find('td').eq(3)[0].children[0].required =false;
            }
//				else{
//				$(this).find('td').eq(1)[0].children[0].required =false;
//				$(this).find('td').eq(2)[0].children[0].required =false;
//				$(this).find('td').eq(3)[0].children[0].required =false;
//				$(this).find('td').eq(4)[0].children[0].required =false;
//				}
        });
        if(calcheck){
            $this.targetObj.find('thead tr th:eq(1)').hide();
            $this.targetObj.find('thead tr th:eq(2)').show();
            $this.targetObj.find('thead tr th:eq(3)').show();
        }else if(!calcheck) {
            $this.targetObj.find('thead tr th:eq(1)').show();
            $this.targetObj.find('thead tr th:eq(2)').hide();
            $this.targetObj.find('thead tr th:eq(3)').hide();
        }
    },
    loadTab:function () {
        var that = this;
        that.targetObj.find('#tabs').carouFredSel({
            circular: false,
            items: 1,
            width: '100%',
            auto: false,
            pagination: {
                container: '#pager',
                anchorBuilder: function( nr ) {
                    var name = $(this).find('h3').attr("id"),className;
                    if(name=='1'){
                        className='tabBg1-2'
                    }else if(name=='5'){
                        className='tabBg2-3'
                    }else{
                        className='tabBg1-3'
                    }
                    return '<a href="#" id="'+name+'" class="'+className+'" onclick="parkOrg.changeColor(this);"><img src="images/tab_'+name+'.png">' + $(this).find('h3').text() + '</a>';
                }
            }
        });
    },
    changeColor:function (obj) {
        var id =obj.id;
        $('#pager a').each(function(){
            if(id=='5'){
                if(this.id =='5'){
                    this.className='tabBg2-2';
                }else{
                    this.className='tabBg1-1';
                }
            }else{
                if(this.id < id){
                    this.className='tabBg1-1';
                }else if(this.id == id){
                    this.className='tabBg1-2';
                }else{
                    if(this.id=='5'){
                        this.className ='tabBg2-3';
                    }else{
                        this.className ='tabBg1-3';
                    }
                }
            }
        });
    },
    createTr : function($tbody, id,item,modelKey) {
        var _this = this;
        var calcheck = $('#calflag').val() == 0 ? false : true;
//			var difcheck = $('#difflag').val() == 0 ? false : true;
        var tr = document.createElement("tr");
//			var td_check = document.createElement("td");
        var td_carType = document.createElement("td");
        var td_chargeNo = document.createElement("td");
        var td_holiday = document.createElement("td");
        var td_working = document.createElement("td");
        var td_mtcharge = document.createElement("td");
        var td_openGate = document.createElement("td");

//			var checkbox = document.createElement("input");
//			checkbox.value = id;
//			checkbox.tabindex = -1;
//			checkbox.type = "checkbox";
//			checkbox.name = "charge_ids";
//			td_check.appendChild(checkbox);

        var carType = document.createElement("select");
        carType.name = "carType";
        carType.required = true;
        carType.setAttribute('data-validate','select');
        td_carType.appendChild(carType);
//			var defaultOption = document.createElement("option");
//			defaultOption.innerHTML = "";
//			carType.appendChild(defaultOption);
//			$(Utils.getModelArrayByParentModelKey(BASIS.VEHICLE_TYPE.ROOT)).each(function (inx, itm) {
        var itm = Utils.getDataDictByModelKey(modelKey);
        var option = document.createElement("option");
        option.innerHTML = itm.modelName;
        option.value = itm.modelValue;
//			if (item && item["carType"] == itm.modelValue) {
        option.setAttribute("selected", "selected")
//			}
        carType.appendChild(option);
//			});

        var chargeNo = document.createElement("select");
        chargeNo.name = "chargeNo";
        chargeNo.setAttribute('data-validate','select');
        td_chargeNo.appendChild(chargeNo);
        var defaultOption = document.createElement("option");
        defaultOption.innerHTML = "";
        chargeNo.appendChild(defaultOption);
        $(_this.chargeList).each(function (inx, itm) {
            var option = document.createElement("option");
            option.innerHTML = itm.name;
            option.value = itm.code;
            if (item && item["chargeNo"] == itm.code) {
                option.setAttribute("selected", "selected")
            }
            chargeNo.appendChild(option);
        });

        var holiday = document.createElement("select");
        holiday.name = "holiday";
        holiday.setAttribute('data-validate','select');
        td_holiday.appendChild(holiday);
        var defaultOption = document.createElement("option");
        defaultOption.innerHTML = "";
        holiday.appendChild(defaultOption);
        $(_this.chargeList).each(function (inx, itm) {
            var option = document.createElement("option");
            option.innerHTML = itm.name;
            option.value = itm.code;
            if (item && item["holiday"] == itm.code) {
                option.setAttribute("selected", "selected")
            }
            holiday.appendChild(option);
        });

        var working = document.createElement("select");
        working.name = "working";
        working.setAttribute('data-validate','select');
        td_working.appendChild(working);
        var defaultOption = document.createElement("option");
        defaultOption.innerHTML = "";
        working.appendChild(defaultOption);
        $(_this.chargeList).each(function (inx, itm) {
            var option = document.createElement("option");
            option.innerHTML = itm.name;
            option.value = itm.code;
            if (item && item["working"] == itm.code) {
                option.setAttribute("selected", "selected")
            }
            working.appendChild(option);
        });

        working.addEventListener('keydown', function(e) {
            if (e.keyCode == 9) {
                if ($(this).parents("tr").next().length < 1) {
                    var $_no_input = $(this).parents("tr").find("select[name=carType]");
                    var _val = $_no_input.val();
                    if (_val == "" || _val == undefined || !_val) {
                        e.returnValue = false;
                        e.cancel = true;
                        $_no_input.focus();
                        return;
                    }
                    e.returnValue = false;
                    e.cancel = true;
                    new chargeBinfo(undefined, _this.targetObj.find("#charge_list")).addToList(_this);
                    _this.targetObj.find("#charge_list tbody tr:last select[name=carType]").focus();
                    return;
                }
            }
        });
        //创建开闸方式下拉列表  A闸 B闸
        var basisGate = Utils.getModelArrayByParentModelKey(BASIS.GATE_TYPE.ROOT);
        var openGate = $("<input style='width:99%;' name='openGate'  required >");
        td_openGate.appendChild(openGate[0]);
        //创建月租收费标准
        var mtChargeSelect = $("<input style ='width:99%;' name= 'mtCharge' required>");
        var mtCharge = "";
        td_mtcharge.appendChild(mtChargeSelect[0]);
        JsonpAjax(baseApiPath + 'access_permission/charge_info/list', undefined, 'json', function(res) {
            mtChargeSelect.kendoDropDownList({
                dataTextField: "name",
                dataValueField: "code",
                dataSource: res
            }).data('kendoDropDownList');
        }, false);

        if(isNotEmpt(item) && isNotEmpt(item["mtCharge"])){
            mtChargeSelect.data("kendoDropDownList").value(item["mtCharge"]);
        }else{
            mtChargeSelect.data("kendoDropDownList").select(0);
        }
//			tr.appendChild(td_check);
        tr.appendChild(td_carType);
        tr.appendChild(td_chargeNo);
        tr.appendChild(td_working);
        tr.appendChild(td_holiday);
        tr.appendChild(td_mtcharge);
        tr.appendChild(td_openGate);
        $tbody[0].appendChild(tr);

        //初始化控件
        var that = this;
        var kendoMultiSelect =  openGate.kendoMultiSelect({
            placeholder:"--请选择--",
            dataTextField:"modelName",
            dataValueField:"modelValue",
            dataSource:basisGate
        }).data("kendoMultiSelect");
        if (item && item["gateType"]) {
            kendoMultiSelect.value(item["gateType"].split(","));
        }
        _this.selectDisable(calcheck);

    },
    deleteRow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        _this.targetObj.find("input[name=\"charge_ids\"]:checked").each(function(inx, itm) {
            $(itm).parents("tr").remove();
        });
    },
    createRow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        new chargeBinfo(undefined, _this.targetObj.find("#charge_list")).addToList(_this);
    },
    //保存收费标准信息
    saveparkOrg:function(e){
        var that =  $(e.target).data("that");
        if(validityForm(that.targetObj)){
            var parkInfo = that.sysUtils.getBindDocJson();
            parkInfo.equipmentManagements_params_settlementTime=kendo.toString(parkInfo.equipmentManagements_params_settlementTime,'HH:mm');
            var url = baseApiPath+"facilities/saveParkInfo?isEdit=" + true;
            var sendJson=parkInfo;
            for(var o in parkInfo){
                if(o.indexOf('_') !=-1){
                    var strArray = o.substring(o.indexOf('_')+1);
                    var name = o.substring(0, o.indexOf('_'));
                    var jsonA = {};
                    jsonA[name] = that.recursionObjectName(strArray,parkInfo[o]) ;
                    delete parkInfo[o];
                    var sendJson =$.extend(true,parkInfo,jsonA);
                }
            }
            var calcheck = $('#calflag').val() == 0 ? false : true;
//				var difcheck = $('#difflag').val() == 0 ? false : true;
            //封装列表数据
//				var boundTable = function (calcheck,difcheck) {

//				}
//				if(calcheck){//
            delete sendJson['equipmentManagements']['charge']['workingDaysStandard'];
            delete sendJson['equipmentManagements']['charge']['holidaySeasonStandard'];
//				boundTable(calcheck,difcheck);
            var jsonD= {equipmentManagements:{charge:{chargelist:{}}}};
            var flagJsonD = false;
            that.targetObj.find("#charge_list > tbody tr").each(function (inx, itm) {
                var cols = $(itm).find("td");
                var carType = $(cols[0]).find("select").val();
                var chargeNo = $(cols[1]).find("select").val();
                var holiday = $(cols[2]).find("select").val();
                var working = $(cols[3]).find("select").val();
                var mtCharge = $(cols[4]).find("input[name='mtCharge']").data("kendoDropDownList").value();
                var openGate = $(cols[5]).find("input[name='openGate']").data("kendoMultiSelect").value();
                if(null == openGate || openGate.length<=0){
                    notification({ title:"提示信息",message:"请选择开闸方式!！"},'info');
                    flagJsonD = true;
                    return;
                }
                if(calcheck){
                    jsonD.equipmentManagements.charge.chargelist["charge"+inx] = JSON.stringify({carType:carType,holiday:holiday,working:working,gateType:openGate.toString(),mtCharge:mtCharge});
                }else if(!calcheck){
                    jsonD.equipmentManagements.charge.chargelist["charge"+inx] = JSON.stringify({carType:carType,chargeNo:chargeNo,gateType:openGate.toString(),mtCharge:mtCharge});
                }
            });
            if(flagJsonD) return;
            //合并json对象
            sendJson = $.extend(true,sendJson,jsonD);
//				}else if(!calcheck){
//				delete sendJson['equipmentManagements']['charge']['holidaySeasonStandard'];
//				}

            JsonpAjax(url,JSON.stringify(sendJson),"json",function(result){
                that.sysUtils.setVariantBindFieldValue(result);
                that.isEdit=true;
                parkTree.localUpdate(result);
            });

        }
    },
    recursionObjectName : function (strArray,val) {
        if (strArray.indexOf('_') == -1){
            var jsonC = {};
            jsonC[strArray]=val;
            return jsonC;
        }
        var name = strArray.substring(0, strArray.indexOf('_'));
        strArray = strArray.substring(strArray.indexOf('_')+1);
        var jsonB = {};
        jsonB[name] = this.recursionObjectName(strArray,val);
        return jsonB;
    }
}
